package com.huizluo.module4.chatroom;

import java.io.*;
import java.net.Socket;

public class Client{

    private Socket socket;
    private String addr;
    private int port;

    public Client(String addr, int port) {
        this.addr = addr;
        this.port = port;
    }

    void connect() throws IOException {
        Socket s = new Socket(addr,port);
        System.out.println("connected to server");
        this.socket = s;
    }

    void send(Message msg) throws IOException {
        System.out.println("send msg");
        ObjectOutputStream op = new ObjectOutputStream(socket.getOutputStream());
        op.writeObject(msg);
        op.flush();
    }

    void recv() {
         MsgRevc msgRevc = new MsgRevc(this.socket);
         new Thread(msgRevc).start();
    }

    void sendFile(File file) throws IOException {
        System.out.println("send file");
        //发送文件
        BufferedInputStream bs = new BufferedInputStream(new FileInputStream(file));
        DataOutputStream dos = new DataOutputStream(this.socket.getOutputStream());

        dos.writeUTF(file.getName());
        dos.flush();
        dos.writeLong(file.length());
        dos.flush();

        System.out.println("开始传输文件");
        byte[] buf = new byte[1024*8];
        int res = 0;
        long progress = 0;
        while ((res = bs.read(buf,0,buf.length))!=-1){
            dos.write(buf,0,res);
            dos.flush();
            progress += res;
            System.out.println("[ " + (100*progress/file.length()) + "% ]");
        }
        System.out.println("文件传输完成");
    }

    void close(){
        try {
            this.socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }



}
